<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="处方编号">
          <el-input v-model="searchForm.prescriptionId" placeholder="请输入处方编号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="开具日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'prescription:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增处方
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        stripe
      >
        <el-table-column label="处方编号" prop="prescriptionId" min-width="120" />
        <el-table-column label="患者姓名" min-width="100">
          <template #default="scope">
            <el-button type="text" @click="viewPatient(scope.row.patientId)">
              {{ scope.row.patientName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="开具医生" prop="doctorName" min-width="100" />
        <el-table-column label="开具科室" prop="departmentName" min-width="120" />
        <el-table-column label="药品数量" width="80">
          <template #default="scope">
            {{ scope.row.items?.length || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="总金额" width="100">
          <template #default="scope">
            <span>¥ {{ formatPrice(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开具日期" min-width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'prescription:read'"
            >
              查看
            </el-button>
            <el-button 
              v-if="scope.row.status === '待审核'"
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'prescription:update'"
            >
              编辑
            </el-button>
            <el-dropdown v-if="scope.row.status !== '已作废'">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-if="scope.row.status === '待审核'" 
                    @click="handleAudit(scope.row)"
                    v-permission="'prescription:audit'"
                  >
                    <el-icon><Check /></el-icon>审核通过
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status === '已审核'" 
                    @click="handleDispense(scope.row)"
                    v-permission="'prescription:dispense'"
                  >
                    <el-icon><Finished /></el-icon>完成发药
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status !== '已作废'" 
                    @click="handleCancel(scope.row)"
                    v-permission="'prescription:cancel'"
                  >
                    <el-icon><Close /></el-icon>作废处方
                  </el-dropdown-item>
                  <el-dropdown-item 
                    @click="handlePrint(scope.row)"
                    v-permission="'prescription:print'"
                  >
                    <el-icon><Printer /></el-icon>打印处方
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { prescriptionAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 日期范围
const dateRange = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  prescriptionId: '',
  patientName: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 格式化价格
const formatPrice = (price) => {
  if (!price && price !== 0) return '--'
  return parseFloat(price).toFixed(2)
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    searchForm.startDate = val[0]
    searchForm.endDate = val[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待审核':
      return 'warning'
    case '已审核':
      return 'success'
    case '已发药':
      return 'primary'
    case '已作废':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取处方列表
const getPrescriptions = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await prescriptionAPI.getPrescriptions(params)
    tableData.value = res.data.prescriptions
    total.value = res.data.total
  } catch (error) {
    console.error('获取处方列表失败', error)
    ElMessage.error('获取处方列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getPrescriptions()
}

// 重置搜索条件
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  searchForm.startDate = ''
  searchForm.endDate = ''
  currentPage.value = 1
  getPrescriptions()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getPrescriptions()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getPrescriptions()
}

// 新增处方
const handleCreate = () => {
  router.push('/prescriptions/create')
}

// 查看处方
const handleView = (row) => {
  router.push(`/prescriptions/detail/${row.id}`)
}

// 编辑处方
const handleEdit = (row) => {
  router.push(`/prescriptions/edit/${row.id}`)
}

// 查看患者
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 审核处方
const handleAudit = (row) => {
  ElMessageBox.confirm('确认审核通过该处方？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await prescriptionAPI.updatePrescription(row.id, { status: '已审核' })
      ElMessage.success('处方审核成功')
      getPrescriptions()
    } catch (error) {
      console.error('处方审核失败', error)
      ElMessage.error(error.message || '处方审核失败')
    }
  }).catch(() => {})
}

// 完成发药
const handleDispense = (row) => {
  ElMessageBox.confirm('确认完成该处方的发药？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await prescriptionAPI.updatePrescription(row.id, { status: '已发药' })
      ElMessage.success('发药操作成功')
      getPrescriptions()
    } catch (error) {
      console.error('发药操作失败', error)
      ElMessage.error(error.message || '发药操作失败')
    }
  }).catch(() => {})
}

// 作废处方
const handleCancel = (row) => {
  ElMessageBox.confirm('确认作废该处方？此操作不可恢复', '警告', {
    confirmButtonText: '确认作废',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      await prescriptionAPI.updatePrescription(row.id, { status: '已作废' })
      ElMessage.success('处方已作废')
      getPrescriptions()
    } catch (error) {
      console.error('作废处方失败', error)
      ElMessage.error(error.message || '作废处方失败')
    }
  }).catch(() => {})
}

// 打印处方
const handlePrint = (row) => {
  // 实际应用中可能会打开一个新窗口进行打印预览
  window.open(`/prescriptions/print/${row.id}`, '_blank')
}

// 页面加载时获取数据
onMounted(() => {
  getPrescriptions()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 